package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.GuiguException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * ClassName: FileUploadServiceImpl
 * Package: com.atguigu.tingshu.album.service.impl
 * Description:
 *
 * @Author ycy
 * @Create 2024/9/5 16:56
 * @Version 1.0
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties props;


    /**
     * 将图片文件上传到 minio
     * @param file 图片文件
     * @return 上传后的图片在线地址
     */
    @Override
    public String imageUpload(MultipartFile file) {

        try {
            // 1.业务校验文件是否为图片，借助 ImageIO 读取图片，继续判断图片文件后缀名是否符合要求，图片长宽
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null){
                throw new GuiguException(400,"图片格式非法！");
            }

            // 2.调用 MinIO-Java 客户端对象将文件上传到 MinIO-文件上传
            // 2.1动态生成上传文件名称 /当日日期/UUID.后缀
            String folderName = "/" + DateUtil.today() + "/";
            String fileName = IdUtil.randomUUID();
            String extName = FileUtil.extName/*此方法用于接受文件路径作为参数，然后通过分析文件路径获取文件后缀名*/(file.getOriginalFilename());

            String objectName = folderName + fileName + "." + extName;

            // 2.2 调用文件上传接口
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(props.getBucketName()).object(objectName)
                            .stream(file.getInputStream(),file.getSize(),-1)
                            .contentType(file.getContentType())
                            .build()
            );

            // 3.拼接上传文件成功后在线地址 http://ip:9000/ 存储空间名称/路径/文件标识名称
            return props.getEndpointUrl() + "/" + props.getBucketName() + objectName;
        } catch (Exception e) {
            log.error("【专辑服务】上传图片文件异常:{}",e);
            throw new RuntimeException(e);
        }

    }
}
